<?php

namespace app\models;

use Yii;
use yii\db\ActiveRecord;

/**
 * 用户账单
 * Class UserBill
 * @package app\models
 *
 * @property integer $id PK
 * @property integer $uid 用户编号
 * @property string $month 月份
 * @property integer $package_id 套餐编号
 * @property float $price 单价
 * @property integer $card_amount 计费卡数量
 * @property float $money 金额
 * @property integer $status 状态
 *
 * @property Package $package 关联套餐
 */
class UserBill extends ActiveRecord
{
    const STATUS_EMPTY = 1; // 空账单等待填充
    const STATUS_WAIT_CONFIRM = 2; // 以计算等待确认
    const STATUS_PUBLISH = 3; // 已确认

    /**
     * 生成用户上个月的空账单
     * 每月1号执行一次
     * @param string $month 月份Ym
     */
    public static function taskGenerateNewBill($month = null)
    {
        if (empty($month)) {
            $month = date('Ym', strtotime('-1 month'));
        }
        if (UserBill::find()->andWhere(['month' => $month])->exists()) {
            Yii::warning('生成用户月【month=' . $month . '】账单时发现已经有当月账单信息。');
            return;
        }
        /** @var User $user */
        foreach (User::find()->andWhere(['status' => User::STATUS_OK])->each() as $user) {
            /** @var UserPackage $userPackage */
            foreach (UserPackage::find()->andWhere(['uid' => $user->id])->each() as $userPackage) {
                $userBill = new UserBill();
                $userBill->uid = $user->id;
                $userBill->month = $month;
                $userBill->package_id = $userPackage->package_id;
                $userBill->price = $userPackage->cost_price;
                $userBill->card_amount = 0;
                $userBill->money = 0;
                $userBill->status = UserBill::STATUS_EMPTY;
                $userBill->save();
            }
        }
    }

    /**
     * 关联套餐
     * @return \yii\db\ActiveQuery
     */
    public function getPackage()
    {
        return $this->hasOne(Package::class, ['id' => 'package_id']);
    }
}
